﻿using System;
using System.Windows;
using System.Windows.Input;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Client
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Title = $"{this.Title} - {System.Reflection.Assembly.GetExecutingAssembly().GetName().Version}";
            Loaded += Frm_Loaded;
        }

        private void Frm_Loaded(object sender, RoutedEventArgs e)
        {
            this.KeyDown += Frm_KeyDown;
        }

        private void Frm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
            {
                var sb = new System.Text.StringBuilder();
                var selectedItems = lv.SelectedItems;

                foreach (ViewModels.ImageEx item in selectedItems)
                {
                    sb.AppendLine(item.FileInfo.FullName);
                }

                Clipboard.SetDataObject(sb.ToString());
            }
        }
    }
}

namespace Client.ViewModels
{
    public class MainWindow_ViewModel : BaseViewModel
    {
        private bool _IsBusy;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set
            {
                _IsBusy = value;
                this.OnPropertyChanged(nameof(IsBusy));
            }
        }

        private ObservableCollection<ImageEx> _ImageList;
        public ObservableCollection<ImageEx> ImageList
        {
            get { return _ImageList; }
            set
            {
                if (_ImageList != null)
                {
                    _ImageList.CollectionChanged -= _ImageList_CollectionChanged;
                }

                _ImageList = value;

                if (_ImageList != null)
                {
                    _ImageList.CollectionChanged += _ImageList_CollectionChanged;
                }

                this.OnPropertyChanged(nameof(ImageList));
                this.OnPropertyChanged(nameof(ImageListInfo));
            }
        }

        public string ImageListInfo
        {
            get
            {
                string r = "共 0 个图片，请导入图片";
                if (this.ImageList != null && this.ImageList.Count > 0)
                {
                    r = $"共 {this.ImageList.Count} 个图片";
                }
                return r;
            }
        }

        private string _SaveFileName;
        public string SaveFileName
        {
            get { return _SaveFileName; }
            set
            {
                _SaveFileName = value;
                this.OnPropertyChanged(nameof(SaveFileName));
            }
        }


        private void _ImageList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.OnPropertyChanged(nameof(ImageList));
            this.OnPropertyChanged(nameof(ImageListInfo));
        }

        public MainWindow_ViewModel()
        {
            this.CMD_Clear = new Command(Clear);
            this.CMD_ImportImages = new Command(ImportImages);
            this.CMD_CreatePDF = new Command(CreatePDF);
            this.CMD_CreateWord = new Command(CreateWord);
        }

        #region 清空

        public Command CMD_Clear { get; private set; }

        void Clear()
        {
            this.SaveFileName = string.Empty;
            this.ImageList?.Clear();
        }

        #endregion

        #region 导入图片

        System.ComponentModel.BackgroundWorker mBgWorker_ImportImages { get; set; }

        public Command CMD_ImportImages { get; private set; }

        void ImportImages()
        {
            try
            {
                // System.Windows.Forms
                var o = new Microsoft.Win32.OpenFileDialog();
                o.RestoreDirectory = true;
                o.Multiselect = true;
                o.Filter = "图片文件|*.bmp;*.jpg;*.png";

                var dr = o.ShowDialog();
                if (dr == null || dr == false)
                {
                    return;
                }

                if (mBgWorker_ImportImages != null && mBgWorker_ImportImages.IsBusy == true)
                {
                    return;
                }

                mBgWorker_ImportImages = new System.ComponentModel.BackgroundWorker();
                mBgWorker_ImportImages.DoWork += (bgSender, bgArgs) =>
                {
                    //// 无法使用由线程创建的图像
                    //ImageEx[] threadArr = new ImageEx[o.FileNames.Length];
                    //for (int index = 0; index < o.FileNames.Length; index++)
                    //{
                    //    threadArr[index] = new ImageEx(index, o.FileNames[index]);
                    //}

                    //bgArgs.Result = threadArr;

                    System.Threading.Thread.Sleep(1000);
                };

                mBgWorker_ImportImages.RunWorkerCompleted += (bgSender, bgResult) =>
                {
                    if (bgResult.Error != null)
                    {

                    }
                    else
                    {
                        if (ImageList == null)
                        {
                            ImageList = new ObservableCollection<ImageEx>();
                        }
                        else
                        {
                            foreach (var item in ImageList)
                            {
                                item.Thumb = null;
                                item.FileInfo = null;
                            }
                            ImageList.Clear();
                            GC.Collect();
                        }

                        //// 线程创建的图片 在主线程中显示就会报错？
                        //ImageEx[] threadArr = bgResult.Result as ImageEx[];
                        //System.Diagnostics.Debug.WriteLine(threadArr.Length);

                        for (int index = 0; index < o.FileNames.Length; index++)
                        {
                            ImageList.Add(new ImageEx(index, o.FileNames[index]));
                        }

                        this.IsBusy = false;
                    }
                };

                IsBusy = true;

                mBgWorker_ImportImages.RunWorkerAsync(new object[] { });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.GetInfo());
                System.Diagnostics.Debugger.Break();
            }
        }

        #endregion

        #region 创建PDF      
        System.ComponentModel.BackgroundWorker mBgWorker { get; set; }


        public Command CMD_CreatePDF { get; private set; }

        void CreatePDF()
        {
            try
            {
                if (this.ImageList.Count <= 0)
                {
                    WPFControls.MessageBox.ShowWarningDialog("请导入图片");
                    return;
                }

                if (this.SaveFileName.IsNullOrWhiteSpace())
                {
                    WPFControls.MessageBox.ShowWarningDialog("请填写生成PDF文件名");
                    return;
                }

                if (mBgWorker != null && mBgWorker.IsBusy == true)
                {
                    return;
                }

                mBgWorker = new System.ComponentModel.BackgroundWorker();
                mBgWorker.DoWork += (bgSender, bgArgs) =>
                {
                    string[] args = new string[this.ImageList.Count];
                    for (int index = 0; index < this.ImageList.Count; index++)
                    {
                        args[index] = this.ImageList[index].FileInfo.FullName;
                    }

                    var saveFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"{this.SaveFileName}.pdf");

                    var filePath = Util.PDF.PDFUtils_Aspose.CreatePDFByImages(saveFilePath, args);
                    bgArgs.Result = filePath;
                };

                mBgWorker.RunWorkerCompleted += (bgSender, bgResult) =>
                {
                    if (bgResult.Error != null)
                    {
                        WPFControls.MessageBox.ShowErrorDialog(bgResult.Error);
                    }
                    else
                    {
                        string filePath = bgResult.Result as string;                        
                        WPFControls.MessageBox.ShowInformationDialog($"创建成功。文件路径\r\n{filePath}");
                        IsBusy = false;
                    }
                };

                IsBusy = true;
                mBgWorker.RunWorkerAsync(new object[] { });

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.GetInfo());
                System.Diagnostics.Debugger.Break();
            }
        }

        #endregion

        #region 创建Word文档

        public Command CMD_CreateWord { get; private set; }

        void CreateWord()
        {
            try
            {
                var saveFilePath = System.IO.Path.Combine
                (
                    Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                    "testWord.docx"
                );

                Util.Word.WordUtils_Aspose.String2Word(saveFilePath, "hell world");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.GetInfo());
            }
        }

        #endregion

    }

    public class ImageEx : System.ComponentModel.INotifyPropertyChanged
    {
        #region INotifyPropertyChanged成员

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName = "")
        {
            this.PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }

        #endregion

        public ImageEx(int index, string path)
        {
            this.Index = index;
            this.FileInfo = new FileInfo(path);
            using (var bitmap = new System.Drawing.Bitmap(path))
            {
                var image = Util.Drawing.DrawingUtils.Resize(bitmap, 60, 80, "HW");
                var bitmapThumb = Util.Drawing.DrawingUtils.Image2Bitmap(image);
                Thumb = Util.Drawing.DrawingUtils.Bitmap2BitmapSource(bitmapThumb);
                bitmap.Dispose();
            }
        }

        /// <summary>
        /// 缩略图
        /// </summary>
        public System.Windows.Media.ImageSource Thumb { get; set; }

        private int _Index;
        public int Index
        {
            get { return _Index; }
            set
            {
                _Index = value;
                this.OnPropertyChanged(nameof(Index));
            }
        }

        public FileInfo FileInfo { get; set; }
    }
}
